package com.xfreelance.qcshop.service;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xfreelance.qcshop.commom.RestBody;
import com.xfreelance.qcshop.configure.DptConfig;
import com.xfreelance.qcshop.entity.Goods;
import com.xfreelance.qcshop.entity.User;
import com.xfreelance.qcshop.exception.DptException;
import com.xfreelance.qcshop.mapper.GoodsMapper;
import com.xfreelance.qcshop.utils.DptUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class GoodsService {
    @Autowired
    private DptConfig dptConfig;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private DptUtil dptUtil;

    public List<Map<String, Object>> getBonusGoods(User user) throws Exception {
        List<String> txmList= new ArrayList<String>() {
            {
                add("6910019016081");
                add("6910019023324");
                add("6910019022563");
                add("6910019015503");
                add("6970032250138");
                add("6910019023416");
            }
        };

        List<Map<String, Object>> goodsList = new ArrayList<>();

        for (String txm : txmList) {
            Map<String, Object> goodsInfo = showTagInfo(txm);
            if (goodsInfo.get("bonusPrice") != null) {
                goodsList.add(goodsInfo);
            }
        }

        return goodsList;
    }


    public Map<String, Object> showTagInfo(String txm) throws Exception {
        Map<String, Object> goods = new HashMap<>();
        // ============ 获取assCode信息 ===============
        String assCode = null;
        Map<String, Object> assBody = new HashMap<>();
        assBody.put("nodeCode", "7005");
        assBody.put("code", txm);

        String assResponse = HttpRequest.post(dptConfig.getDomain()+"/Retailing/LoadGoodsAssociateByCodeForApp")
                .body(JSONUtil.toJsonStr(assBody))
                .timeout(20000)//超时，毫秒
                .execute().body();
        String errorMessage = JSONUtil.parseObj(assResponse).getStr("ErrorMessage");
        if (errorMessage == null || errorMessage.length() > 0) {
            System.out.println("error message: " + errorMessage);
            throw new Exception(errorMessage);
        }

        JSONArray obj = JSONUtil.parseObj(assResponse).getJSONArray("obj");
        for (Object o : obj) {
            assCode = ((JSONObject) o).getStr("AssCode");
        }

        // ============ 获取商品信息 ===============
        Map<String, Object> detailBody = new HashMap<>();
        detailBody.put("nodeCode", "7005");
        detailBody.put("goodscode", assCode);

        String detailresponse = HttpRequest.post(dptConfig.getDomain() + "/Retailing/GetPriceTagGoodsInfo")
                .body(JSONUtil.toJsonStr(detailBody))
                .timeout(20000)//超时，毫秒
                .execute().body();
        String detailerrorMessage = JSONUtil.parseObj(detailresponse).getStr("ErrorMessage");
        if (detailerrorMessage == null || detailerrorMessage.length() > 0) {
            System.out.println("error message: " + detailerrorMessage);
            throw new Exception(errorMessage);
        }

        JSONArray detailobj = JSONUtil.parseObj(detailresponse).getJSONArray("obj");
        detailobj.forEach(o -> {
            JSONObject jsonObject = (JSONObject) o;
            goods.put("imgUrl", "微信图片_20240325132448.jpg");
            goods.put("title", jsonObject.getStr("商品名称"));
            goods.put("originPrice", jsonObject.getStr("销售单价").replace("￥", ""));
            goods.put("inventry", jsonObject.getInt("库存数量"));
            goods.put("shelf", jsonObject.getStr("shelf"));
            goods.put("txm", jsonObject.getStr("商品条码"));
        });


        Map<String, String> promotionBody = new HashMap<>();
        promotionBody.put("nodeCode", "7005");
        promotionBody.put("goodscode", assCode);
        promotionBody.put("queryCode", "02");

            String promotionResponse = HttpRequest.post(dptConfig.getDomain() + "/Retailing/GetPromotionInformation")
                    .formStr(promotionBody)
                    .body(JSONUtil.toJsonStr(promotionBody))
                    .timeout(20000)//超时，毫秒
                    .execute().body();
            String promotionErrorMessage = JSONUtil.parseObj(promotionResponse).getStr("ErrorMessage");
            if (promotionErrorMessage == null || promotionErrorMessage.length() > 0) {
                System.out.println("error message: " + promotionErrorMessage);
                throw new Exception(errorMessage);
            }

            JSONArray promotionObj = JSONUtil.parseObj(promotionResponse).getJSONArray("obj");
            for (Object o : promotionObj) {
                String bonusPrice = ((JSONObject) o).getStr("促销单价");
                goods.put("bonusPrice", bonusPrice.replace("￥", ""));
            }

        // =========== 获取每日销量 =================
        Map<String, String> SaleBody = new HashMap<>();
        SaleBody.put("nodeCode", "7005");
        SaleBody.put("goodscode", assCode);
        String saleResponse = HttpRequest.post(dptConfig.getDomain() + "/Retailing/LoadGoodsPSSMSaleAmount")
                .formStr(SaleBody)
                .timeout(20000)//超时，毫秒
                .execute().body();
        String saleErrorMessage = JSONUtil.parseObj(saleResponse).getStr("ErrorMessage");
        if (saleErrorMessage == null || saleErrorMessage.length() > 0) {
            System.out.println("error message: " + saleErrorMessage);
            throw new Exception(errorMessage);
        }

        goods.put("saleNum", JSONUtil.parseObj(saleResponse).getJSONObject("obj").getInt("SumSaleAmount"));

        return goods;
        }

        public Goods getGoodsByCode(String code) {
            QueryWrapper<Goods> goodsWrapper = new QueryWrapper<>();
            goodsWrapper.eq("code", code);
            Goods goods = goodsMapper.selectOne(goodsWrapper);
            return goods;
        }

        public void add(Goods goods) {
            goodsMapper.insert(goods);
        }
}
